<template>
  <Dialog :appDialog="appDialog" ref="dialogRef">
    <template v-if="type">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <!-- 分组 -->
        <el-form-item label="分组">
          <el-cascader
            style="width: 100%"
            v-model="form.group"
            :options="groupData"
            :props="defaultProps"
            placeholder="请选择分组"
          />
        </el-form-item>
        <!-- 标题 -->
        <template>
          <el-form-item label="标题">
            <el-input
              v-model="form.title"
              maxlength="12"
              show-word-limit
              :placeholder="`请输入${labelName[type]}标题`"
            ></el-input>
          </el-form-item>
        </template>
        <!-- 类型 -->
        <template v-if="[2, 4, 5].includes(type)">
          <el-form-item label="类型">
            <el-radio-group v-model="form.type" class="radio_list">
              <el-radio
                v-for="item in typeDiff(type)"
                :key="item.value"
                :label="item.value"
                class="radio_list_item"
              >
                <span class="radio_list_item_text">{{ item.name }}</span>
                <el-tooltip
                  v-if="item.value === 1"
                  :content="item.text"
                  placement="bottom"
                  effect="light"
                >
                  <div class="radio_list_item_icon radio_img">
                    <img src="@/assets/image/material/question.png" alt="" />
                  </div>
                </el-tooltip>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <template v-if="type == 6"></template>
        <!-- 链接地址 -->
        <template v-if="type == 6">
          <el-form-item label="链接地址">
            <el-input type="text" v-model="form.link" placeholder="请输入链接地址"></el-input>
          </el-form-item>
          <!-- 连接描述 -->
          <el-form-item label="链接描述">
            <el-input
              type="textarea"
              v-model="form.linkDesc"
              :rows="2"
              maxlength="1000"
              show-word-limit
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </template>
        <!-- 上传文件 -->
        <ZWUpload :upInfo="upLoadType[type]" @submit="getFileList" ref="emptyData" />
        <!-- 标签 -->
        <el-form-item label="标签">
          <el-scrollbar v-if="form.tags && form.tags.length > 0" max-height="100px">
            <el-tag
              class="mr10"
              type="warning"
              v-for="tag in form.tags"
              :key="tag.id"
              plain
              closable
              :disable-transitions="false"
              @close="handleClose(tag.id)"
            >
              {{ tag.name }}
            </el-tag>
          </el-scrollbar>
          <el-button type="primary" plain @click="openTag" size="small">请选择标签</el-button>
        </el-form-item>
        <el-form-item label="">
          <div class="agree_ment">
            <el-checkbox v-model="form.check" @change="confirmSure"></el-checkbox>
            <span class="ml2">勾选代表同意</span>
            <el-link class="form-link" type="primary" :underline="false">《***用户协议》</el-link>
          </div>
        </el-form-item>
      </el-form>
    </template>
  </Dialog>
  <!-- 标签弹框 -->
  <ZWSelectTag ref="uploadSelectRef" @submit="getTags" />
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onUnmounted } from 'vue'
import Dialog from './Dialog.vue'
import ZWUpload from '@/components/ZWUpload.vue'
import ZWSelectTag from '@/components/ZWSelectTag.vue'
import {
  modifyImage,
  imagesInfo,
  uploadImage,
  createdFile,
  uplodVoice,
  getVoiceInfo,
  quickLink,
  getFileInfo,
  updateFile,
  updateLink,
  linkInfos,
  changeVoice
} from '@/api/concreation'
import { ElForm, ElMessage } from 'element-plus'
import { getSetionId } from '@/utils/utils'
import bus from '@/utils/bus'
const formRef = ref<InstanceType<typeof ElForm>>()
const emit = defineEmits(['submit'])
import { useStore } from '@/store'
const store = useStore()
const uploadSelectRef = ref(null)
const uploadTitle = ref('上传文件')
let codeArr = reactive([])
const codeDetail = ref()
const uploadVisib = ref(false)
const dialogRef = ref(null)
const imageId = reactive({
  media_content_id: ''
}) // 编辑图片 id
const isEdit = ref(false)
const editType = ref(0)
const emptyData = ref() // 清空回显数据
// 1-文本 2-图片 3-音频 4-视频 5-文件 6-链接文章 7-链接引用
const type = computed(() => {
  return store.getters['content/type']
})
//上传弹框
const uploadInfo = computed(() => {
  return store.getters['content/upload']
})
// 分组列表
const group = computed(() => {
  return store.getters['content/group']
})
//标签
const tags = computed(() => {
  return store.getters['content/tagsInfo'].tags
})
const defaultProps = {
  checkStrictly: true,
  emitPath: false,
  label: 'name',
  value: 'id'
}
// 分组 tree
const groupData = ref([])

const form = reactive({
  group: 0, //分组
  type: 0,
  images: [], // 图片
  video: 'code ', // 音频文件
  audio: '', // 视频文件
  files: '', //文件
  tags: [], //标签
  check: true, //用户协议
  title: '', //标题
  link: '', //链接地址
  cover: '', //连接封面
  linkDesc: '', // 连接描述
  id: '' //内容id
})

const rules = reactive({
  images: [
    {
      required: true,
      message: '图片不能为空',
      trigger: 'click'
    }
  ],
  video: [
    {
      required: true,
      message: '视频不能为空',
      trigger: 'click'
    }
  ],
  files: [
    {
      required: true,
      message: '文件不能为空',
      trigger: 'click'
    }
  ],
  audio: [
    {
      required: true,
      message: '语音不能为空',
      trigger: 'click'
    }
  ],
  cover: [
    {
      required: true,
      message: '封面不能为空',
      trigger: 'click'
    }
  ]
})
// 图片上传
const picInfo = reactive({
  type: 1,
  label: '图片',
  prop: 'images',
  files: form.images,
  multiple: true,
  limitSize: 2,
  limitNum: 9,
  acceptFile: '.jpg,.jpeg,.png,.gif,.bmp,.webp'
})
// 文件上传
const fileInfo = reactive({
  type: 2,
  label: '文件',
  prop: 'files',
  files: form.files,
  multiple: false,
  limitSize: 20,
  limitNum: 1,
  acceptFile: '.DOC,.DOCX,.XLS,.XLSX,.CSV,.PPT,.PPTX,.TXT,.PDF,.Xmind'
})
// 视频上传
const videoInfo = reactive({
  type: 3,
  label: '视频',
  prop: 'video',
  files: form.audio,

  multiple: false,
  limitSize: 10,
  acceptFile: '.mp4'
})
// 语音上传
const audioInfo = reactive({
  type: 4,
  label: '语音',
  prop: 'audio',
  files: form.video,
  multiple: false,
  limitSize: 200,
  acceptFile: '.mp3,.wma,.wav,.amr,.m4a'
})
//封面上传
const linkInfo = reactive({
  type: 1,
  label: '封面',
  prop: 'cover',
  file: form.cover,
  limitSize: 2,
  limitNum: 1,
  multiple: false,
  acceptFile: '.jpg,.jpeg,.png,.gif,.bmp,.webp'
})
const labelName = reactive(['', '', '图片', '', '视频', '文件', '链接'])
const upLoadType = reactive(['', '', picInfo, audioInfo, videoInfo, fileInfo, linkInfo, fileInfo])

const typeDiff = (type: number) => {
  return [
    { value: 0, name: `普通${labelName[type]}` },
    {
      value: 1,
      name: `雷达${labelName[type]}`,
      text: `雷达${labelName[type]}可以追踪客户端浏览次数、时间等数据`
    }
  ]
}
// 获取上传成功的文件
const getFileList = (data: any) => {
  if (type.value == 2) {
    codeArr = getSetionId('code', data)
    console.log(codeArr, 'codeArr-----------')
  } else {
    codeDetail.value = data[0].code
  }
  switch (type.value) {
    case 2:
      form.images = codeArr
      break
    case 3:
      form.audio = data
      console.log(form.audio, '326')
      break
    case 4:
      form.video = codeDetail.value

      break
    case 5:
      form.files = codeDetail.value
    case 6:
      form.cover = codeDetail.value
  }
}
const confirmSure = (val:boolean)=>{
  appDialog.isDisable = !val
}
// 取消
const cancelHandel = () => {
  appDialog.visible = false
  isEdit.value = false
  delUpform()
  console.log(isEdit.value)
  formRef.value.resetFields()
}
//确定
const submitHandel = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      let params = {
        title: form.title,
        group_id: form.group,
        file_type: form.type,
        code: '',
        tag_ids: getSetionId('id', form.tags),
        media_content_id: form.id,
        link: '',
        desc: '',
        cover_code: '',
        tags: getSetionId('id', form.tags)
      }
      try {
        // 修改
        if (isEdit.value) {
          // 图片编辑
          if (type.value == 2) {
            params.code = form.images[0]
            console.log(params, 'wen')
            modifyImage(params).then((data: any) => {
              isEdit.value = false
              ElMessage.success('修改成功')
              emit('submit')
              cancelHandel()
            })
            console.log('def')
          }
          // 修改音频
          if (type.value == 3) {
            params.code = form.audio
            console.log(form.audio)
            changeVoice(params)
              .then((res: any) => {
                emit('submit')
                ElMessage.success('修改成功')
                cancelHandel()
              })
              .catch((err: any) => {
                ElMessage.error(err.msg)
              })
          }
          //修改文件
          if (editType.value == 5) {
            params.code = form.files
            updateFile(params).then((data: any) => {
              console.log(data)
              //修改文件成功
            })
          }
          //修改链接
          if (editType.value == 6) {
            params.code = form.cover
            updateLink(params).then((data: any) => {
              console.log(data)
              //修改链接成功
            })
          }
        } else {
          //文件上传
          if (type.value == 5) {
            params.code = form.files
            createdFile(params)
              .then((res: any) => {
                ElMessage.success('文件上传成功！')
                emit('submit')
                cancelHandel()
                bus.emit('delUpform')
              })
              .catch((err: any) => {
                console.log(err)
              })
          }
          // 图片上传
          if (type.value == 2) {
            params.code = form.images
            uploadImage(params)
              .then((res: any) => {
                emit('submit')
                bus.emit('delUpform')
                ElMessage.success('图片创建成功')
                cancelHandel()
              })
              .catch((err: any) => {
                console.log(err)
              })
          }
          // 创建音频
          if (type.value == 3) {
            params.code = form.audio
            console.log(params.code)
            uplodVoice(params)
              .then((res: any) => {
                emit('submit')
                ElMessage.success('上传音频成功')
                cancelHandel()
              })
              .catch((err: any) => {
                console.log(err)
              })
          }
          //链接封面上传
          if (type.value == 6) {
            params.cover_code = form.cover
            ;(params.link = form.link), //链接地址
              (params.desc = form.linkDesc) //连接描述
            quickLink(params)
              .then((res: any) => {
                ElMessage.success('快速创建链接成功！')
                emit('submit')
                bus.emit('delUpform')
                cancelHandel()
              })
              .catch((err: any) => {
                console.log(err)
              })
          }
        }
      } catch (e) {
        console.log(e)
      }
    }
  })
}
const appDialog = reactive({
  visible: uploadVisib,
  title: uploadTitle,
  width: '670px',
  cancel: cancelHandel,
  submit: submitHandel,
  isDisable:false,
  cancelText: '取消',
  submitText: '保存'
})
//获取编辑内容
const editItem = (data: any) => {
  isEdit.value = true
  const params = {
    media_content_id: data.media_content_id
  }
  if (data.type == 5) {
    editType.value = 5
    //获取文件详情
    getFileInfo(params).then((data: any) => {
      form.title = data.title
      form.group = data.group_id
      form.tags = data.tagInfo
      form.type = data.is_radar
      form.id = data.id
    })
  } else if (type.value == 2) {
    imageId.media_content_id = data.id
    imagesInfo(imageId).then((data: any) => {
      form.title = data.title
      form.group = data.group_id
      form.images = data.mediaFileInfo[0].code
      form.tags = data.tagInfo
      form.type = data.is_radar
      form.id = data.id
      bus.emit('echo', data.mediaFileInfo)
    })
  } else if (type.value == 3) {
    imageId.media_content_id = data.id
    getVoiceInfo(imageId).then((data: any) => {
      form.title = data.title
      form.group = data.group_id
      form.tags = data.tag_info
      form.audio = data.media_content_media.media_file.code
      form.id = data.id
      bus.emit('echo', data)
      console.log(data, 'yaoyao', form)
    })
  } else if (data.type == 6) {
    editType.value = 6
    linkInfos(params).then((data: any) => {
      form.title = data.title
      form.group = data.group_id
      form.tags = data.tags
      form.type = data.is_radar
      form.id = data.id
      form.cover = data.link_info.cover_image_url
      form.link = data.link_info.ref_url
      form.linkDesc = data.desc
      bus.emit('echo', data.link_info)
    })
  }
}
// 清空上传表单数据
const delUpform = () => {
  Object.keys(form).map((key) => {
    console.log(key, '清空')
    if (key !== 'group' && key !== 'type' && key !== 'check') {
      delete form[key]
    }
  })
  emptyData.value.empty()
}
bus.on('delUpform', delUpform)
bus.on('editItem', editItem)
watch(uploadInfo, (uploadInfo) => {
  console.log(uploadInfo, '====uploadInfo')
  uploadTitle.value = uploadInfo.title
  uploadVisib.value = uploadInfo.uploadVisib
})
watch(group, (data) => {
  groupData.value = data.groupList
  form.group = data.groupId
})
watch(tags, (data) => {
  form.tags = data
})
watch(()=>form.check,(val)=>{
  dialogRef.value.disabled =val
})
const openTag = () => {
  uploadSelectRef.value.showCreatTag = true
  uploadSelectRef.value.appDialog.visible = true
  uploadSelectRef.value.selectTags = form.tags
}
// 获取标签
const getTags = (data: any) => {
  form.tags = data
}
// 删除标签
const handleClose = (tag: string) => {
  const arr = form.tags.filter((item: any) => item.id != tag)
  form.tags = arr
}

onUnmounted(() => {
  bus.off('editItem', editItem)
})
</script>

<style lang="scss" scoped>
.radio_list {
  &_item {
    &_icon {
      width: 14px;
      height: 14px;
      margin: -3px 0 0 6px;
      img {
        margin-top: 2px;
        width: 100%;
        height: 100%;
        vertical-align: top;
      }
    }
  }
  :deep .el-radio__label {
    display: flex;
    align-items: center;
  }
}
.ml2 {
  margin-left: 2px;
}
.mr10 {
  margin-right: 10px;
}
.agree_ment {
  display: flex;
  align-items: center;
}
:deep .el-scrollbar {
  height: 50%;
}
</style>
